package com.wanqh.reptitle.controller;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.wanqh.reptitle.pojo.ProductExcel;
import com.wanqh.reptitle.utils.ExcelUtil;
import com.wanqh.reptitle.utils.SpiderUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class ZhihuController {

    @GetMapping("/getData")
    public List<String> getData() {
        return SpiderUtils.getData().stream().filter(o -> StringUtils.isNotBlank(o.getBrand()))
                .map(ProductExcel::getBrand).collect(Collectors.toList());
    }

    @PostMapping("/pareHtml")
    public boolean pareHtml(@RequestBody String htmlStr, @RequestParam("brand") String brand) throws Exception {
        String[][] result = new String[][]{{brand}};
        try {
            // 等待页面加载完成
            Document parse = Jsoup.parse(JSON.parseObject(htmlStr).getString("htmlStr"));
            Element searchMainEle = parse.getElementById("SearchMain");
            if(searchMainEle != null) {
                Element attr = searchMainEle.attr("data-za-detail-view-path-index", "0");
                if(attr != null) {
                    Elements h2Eles = attr.getElementsByTag("h2");
                    if(CollUtil.isNotEmpty(h2Eles)) {
                        Element headEle = h2Eles.get(0);
                        Element topicLink = headEle.getElementsByClass("TopicLink").get(0);
                        String href = "https:" + topicLink.attr("href");
                        String text = topicLink.getElementsByClass("Highlight").get(0).text();
                        if(SpiderUtils.isContains(text, brand)){
                            result[0] = new String[]{brand, text, href};
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("解析页面异常！",e);
//            result[0][1] = "异常";
        } finally {
            System.out.println(JSON.toJSONString(result));
            ExcelUtil.appendToExcel("知乎", result, SpiderUtils.FILE_PATH);
        }
        return true;
    }

    @GetMapping("/appendExcel")
    public boolean appendExcel(@RequestParam(name = "sheet", defaultValue = "知乎") String sheet,
                               @RequestParam(name = "brand", defaultValue = "") String brand,
                               @RequestParam(name = "text", defaultValue = "") String text,
                               @RequestParam(name = "href", defaultValue = "") String href) throws Exception {

        String[][] result = new String[][]{{brand, text, href}};
        ExcelUtil.appendToExcel(sheet, result, SpiderUtils.FILE_PATH);
        return true;
    }
}
